<template>
  <div>
    <div class="mb-3 text-right">
      <el-button icon="el-icon-refresh" @click="getData()">刷新</el-button>
      <el-button icon="el-icon-plus" type="primary" @click="handleEdit()">登记</el-button>
    </div>

    <c-table border v-loading="loading" :columns="tableColumns" :data="tableData"></c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <after-register-dialog
      :visible.sync="editVisible"
      :register-data="editRow"
      :related-id="relatedId"
      :table-id="editId"
      @success="handleEditSuccess"
      @change-status="handleChangeStatus"
    ></after-register-dialog>
    <el-dialog :visible.sync="attachVisible" title="详情" append-to-body>
      <after-register-view :form-data="formData"></after-register-view>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { arrayFromString } from '@vimi/utils-tool'

import { deleteAfterIndex } from '@/common/plugins/tools/common'
import { deleteOss } from '@/common/api/oss'
// import { enumSubmitType } from '@/gov/plugins/enum'

import AfterRegisterDialog from '@/credit/views/city/self/after/AfterRegisterDialog'
import { enumCheckMethod, enumCheckType } from '@/credit/views/city/self/after/enum'
import AfterRegisterView from '@/credit/views/city/self/after/AfterRegisterView'
export default {
  components: {
    AfterRegisterDialog,
    AfterRegisterView,
  },
  props: {
    relatedId: String,
  },
  data() {
    return {
      params: {
        index: 1,
        size: 10,
        'customer_related_id.eq': '',
      },
      order: {
        check_date: 'DESC',
      },
      loading: false,
      tableName: 'loan_beh_check',
      totalCount: 0,
      tableData: [],
      tableColumns: [
        {
          attrs: { label: '检查时间', prop: 'check_date', align: 'center' },
          process: v => this.$utils.dateFormat(v, 'yyyy-MM-dd'),
        },
        { attrs: { label: '批次号', prop: 'batch_no', align: 'center' } },
        { attrs: { label: '登记机构', prop: 'submit_client_name', align: 'center' } },
        { attrs: { label: '检查人', prop: 'check_person', align: 'center' } },
        { attrs: { label: '检查方式', prop: 'checkMethod', align: 'center' } },
        { attrs: { label: '检查类型', prop: 'checkType', align: 'center' } },
        { attrs: { label: '检查内容', prop: 'check_des', align: 'center', width: 150 } },
        {
          attrs: { label: '操作', align: 'center', width: 120 },
          operations: [
            {
              content: '查看',
              icon: 'fa fa-search',
              attrs: { class: 'p-0 mx-2' },
              event: this.handleAttachMent,
            },
            {
              content: '修改',
              icon: 'fa fa-edit',
              event: this.handleEdit,
              attrs: { class: 'p-0 mx-2' },
              ifRender: row => row.submit_person === this.userId,
            },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger p-0 mx-2' },
              event: this.hanleDelete,
              ifRender: row => row.submit_person === this.userId,
            },
          ],
        },
      ],

      editId: '',
      editVisible: false,
      editRow: {},
      attachVisible: false,
      attachImages: [],
      customerName: '',
      formData: {},
    }
  },
  computed: {
    ...mapGetters(['userId']),
  },
  watch: {
    relatedId: {
      handler: function () {
        this.getData()
        this.getRelated()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    handleAttachMent(row) {
      this.formData = { ...row }
      this.attachVisible = true
    },
    getRelated() {
      if (!this.relatedId) return
      const params = {
        'customer_related_id.eq': this.relatedId,
        fields: ['customer_name'],
      }
      this.$api.getData(this.$serviceName, 'customer_related', params).then(res => {
        const data = res?.data?.[0] ?? {}
        this.customerName = data.customer_name || ''
      })
    },
    async getData() {
      if (!this.relatedId) return
      this.params['customer_related_id.eq'] = this.relatedId

      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, this.params, this.order)
      )
      this.loading = false

      const data = (res && res.data) || {}
      this.totalCount = data.totalCount || 0
      this.tableData = (data.data || []).map(this.dataAdapter)
    },
    dataAdapter(item) {
      item.checkMethod = enumCheckMethod[item.check_method]
      item.checkType = enumCheckType[item.check_type]
      return item
    },
    handleEdit(row = {}) {
      this.editId = row.loan_beh_check_id || ''
      this.editRow = { ...row, customer_name: this.customerName }
      this.editVisible = true
    },
    handleEditSuccess() {
      this.getData()
    },
    hanleDelete(row) {
      this.$utils
        .msgbox({
          message: `确定删除此条登记?`,
          beforeClose: () => this.deleteData(row.loan_beh_check_id, row.check_attachment),
        })
        .then(() => {
          this.$message.success('删除成功！')
          this.params.index = deleteAfterIndex(this.tableData.length, this.params.index)
          this.getData()
        })
        .catch(() => this.$message.error(`删除失败，请重试！`))
    },
    deleteData(id, imgStr) {
      const imgArray = arrayFromString(imgStr)
      if (!imgArray.length) {
        return this.$api.deleteData(this.$serviceName, this.tableName, id)
      } else {
        return Promise.all([
          this.$api.deleteData(this.$serviceName, this.tableName, id),
          deleteOss(imgArray),
        ])
      }
    },
    handleChangeStatus(res) {
      this.$emit('change-status', res)
    },
  },
}
</script>
<style lang="scss" scoped></style>
